package com.ext.aic.handler;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.graphics.Path;
import android.os.Handler;
import android.os.Looper;

import com.eyinfo.android_pure_utils.HandlerManager;
import com.eyinfo.android_pure_utils.events.RunnableParamsN;

public class AccessibilityClickHandler {

    private int retry = 0;

    protected void onTriggerClickSuccess(GestureDescription gesture) {

    }

    /**
     * 模拟点击指定坐标
     *
     * @param service    无障碍服务实例
     * @param x          目标X坐标（物理像素）
     * @param y          目标Y坐标（物理像素）
     * @param retryCount 重试次数
     */
    public void clickAtPoint(AccessibilityService service, float x, float y, int retryCount, boolean forceRetry, int duration) {
        retry++;
        Path path = new Path();
        path.moveTo(x, y);
        path.lineTo(x + 1, y + 1);
        GestureDescription.StrokeDescription stroke =
                new GestureDescription.StrokeDescription(path, 0, duration);
        GestureDescription.Builder builder = new GestureDescription.Builder();
        builder.addStroke(stroke);
        try {
            boolean dispatched = service.dispatchGesture(builder.build(), new AccessibilityService.GestureResultCallback() {
                @Override
                public void onCompleted(GestureDescription gesture) {
                    delayTrigger(gesture);
                }

                @Override
                public void onCancelled(GestureDescription gestureDescription) {
                    if (forceRetry && (retry < retryCount)) {
                        clickAtPoint(service, x, y, retryCount, forceRetry, 200);
                    }
                }
            }, new Handler(Looper.getMainLooper()));
            if (!dispatched && forceRetry && (retry < retryCount)) {
                clickAtPoint(service, x, y, retryCount, forceRetry, 200);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (forceRetry && (retry < retryCount)) {
                clickAtPoint(service, x, y, retryCount, forceRetry, 200);
            }
        }
    }

    public void clickAtPoint(AccessibilityService service, float x, float y) {
        clickAtPoint(service, x, y, 1, false, 200);
    }

    public void clickAtPoint(AccessibilityService service, float x, float y, int duration) {
        clickAtPoint(service, x, y, 1, false, duration);
    }

    private void delayTrigger(GestureDescription gesture) {
        HandlerManager.getInstance().postDelayed(new RunnableParamsN<Object>() {
            @Override
            public void run(Object... objects) {
                onTriggerClickSuccess(gesture);
            }
        }, 500);
    }
}
